<?php

namespace app\adminapi\controller;

use app\model\TopicModel;
use app\model\PostModel;
use app\model\UsersModel;
use Webman\Http\Request;

class Topic extends BaseAdminApi
{
    protected ?string $dataModel = TopicModel::class;
    protected array $with = [];
    protected array $allowSearch = ['name', 'description', 'status', 'creator_id'];

    /**
     * 获取圈子详情
     */
    public function getTopicDetail(Request $request)
    {
        $id = $request->get('id');
        if (empty($id)) {
            return $this->fail('圈子ID不能为空');
        }

        $topic = TopicModel::with(['user:id,nickname,avatar'])
            ->find($id);

        if (!$topic) {
            return $this->fail('圈子不存在');
        }

        return $this->success($topic, '获取成功');
    }

    /**
     * 更新圈子状态
     */
    public function updateTopicStatus(Request $request)
    {
        $id = $request->post('id');
        $status = $request->post('status');

        if (empty($id)) {
            return $this->fail('圈子ID不能为空');
        }

        if (!in_array($status, [0, 1, 2])) {
            return $this->fail('状态值无效');
        }

        $topic = TopicModel::find($id);
        if (!$topic) {
            return $this->fail('圈子不存在');
        }

        try {
            $topic->status = $status;
            $topic->save();

            $statusText = ['关闭', '正常', '广场推荐'];
            return $this->success('圈子状态已更新为：' . $statusText[$status]);
        } catch (\Exception $e) {
            return $this->fail('更新失败：' . $e->getMessage());
        }
    }

    /**
     * 删除圈子
     */
    public function deleteTopic(Request $request)
    {
        $id = $request->post('id');
        if (empty($id)) {
            return $this->fail('圈子ID不能为空');
        }

        $topic = TopicModel::find($id);
        if (!$topic) {
            return $this->fail('圈子不存在');
        }

        try {
            // 检查圈子下是否有帖子
            $postCount = PostModel::where('topic_id', $id)->count();
            if ($postCount > 0) {
                return $this->fail('该圈子下还有 ' . $postCount . ' 个帖子，请先删除所有帖子后再删除圈子');
            }

            $topic->delete();
            return $this->success('删除成功');
        } catch (\Exception $e) {
            return $this->fail('删除失败：' . $e->getMessage());
        }
    }

    /**
     * 批量删除圈子
     */
    public function batchDeleteTopics(Request $request)
    {
        $ids = $request->post('ids');
        if (empty($ids) || !is_array($ids)) {
            return $this->fail('请选择要删除的圈子');
        }

        try {
            // 检查是否有圈子下还有帖子
            $topicsWithPosts = [];
            foreach ($ids as $id) {
                $postCount = PostModel::where('topic_id', $id)->count();
                if ($postCount > 0) {
                    $topic = TopicModel::find($id);
                    if ($topic) {
                        $topicsWithPosts[] = $topic->name . '(' . $postCount . '个帖子)';
                    }
                }
            }

            if (!empty($topicsWithPosts)) {
                return $this->fail('以下圈子下还有帖子，请先删除帖子：' . implode('、', $topicsWithPosts));
            }

            TopicModel::whereIn('id', $ids)->delete();
            return $this->success('批量删除成功');
        } catch (\Exception $e) {
            return $this->fail('批量删除失败：' . $e->getMessage());
        }
    }

    /**
     * 编辑圈子信息
     */
    public function saveTopic(Request $request)
    {
        $params = $request->post();

        $rules = [
            'name' => 'required|max:20',
            'description' => 'nullable|max:255',
            'status' => 'required|in:0,1,2',
            'notice' => 'nullable|max:1000'
        ];

        $messages = [
            'name.required' => '圈子名称不能为空',
            'name.max' => '圈子名称不能超过20个字符',
            'description.max' => '圈子描述不能超过255个字符',
            'status.required' => '状态不能为空',
            'status.in' => '状态值只能是0、1或2',
            'notice.max' => '公告不能超过1000个字符'
        ];

        $validator = validator($params, $rules, $messages);

        if ($validator->fails()) {
            return $this->fail($validator->errors()->first());
        }

        try {
            if (isset($params['id']) && !empty($params['id'])) {
                // 编辑圈子
                $topic = TopicModel::find($params['id']);
                if (!$topic) {
                    return $this->fail('圈子不存在');
                }

                // 检查圈子名称是否重复（排除自己）
                $existTopic = TopicModel::where('name', $params['name'])
                    ->where('id', '!=', $params['id'])
                    ->first();
                if ($existTopic) {
                    return $this->fail('圈子名称已存在');
                }

                $updateData = [
                    'name' => $params['name'],
                    'description' => $params['description'] ?? '',
                    'status' => $params['status'],
                    'notice' => $params['notice'] ?? ''
                ];

                $topic->update($updateData);
                return $this->success('圈子更新成功');
            } else {
                return $this->fail('创建圈子功能暂未开放，请通过前端应用创建');
            }
        } catch (\Exception $e) {
            return $this->fail('操作失败：' . $e->getMessage());
        }
    }

    /**
     * 获取圈子统计信息
     */
    public function getTopicStatistics(Request $request)
    {
        try {
            $totalTopics = TopicModel::count();
            $activeTopics = TopicModel::where('status', 1)->count();
            $recommendedTopics = TopicModel::where('status', 2)->count();
            $closedTopics = TopicModel::where('status', 0)->count();
            
            $todayTopics = TopicModel::whereDate('created_at', date('Y-m-d'))->count();
            $weekTopics = TopicModel::where('created_at', '>=', date('Y-m-d', strtotime('-7 days')))->count();
            $monthTopics = TopicModel::where('created_at', '>=', date('Y-m-d', strtotime('-30 days')))->count();

            // 热门圈子（按成员数量排序）
            $hotTopics = TopicModel::select('id', 'name', 'user_num', 'post_num')
                ->orderBy('user_num', 'desc')
                ->limit(10)
                ->get();

            // 活跃圈子（按帖子数量排序）
            $activeTopicsByPosts = TopicModel::select('id', 'name', 'user_num', 'post_num')
                ->orderBy('post_num', 'desc')
                ->limit(10)
                ->get();

            return $this->success('获取统计信息成功', [
                'total_topics' => $totalTopics,
                'active_topics' => $activeTopics,
                'recommended_topics' => $recommendedTopics,
                'closed_topics' => $closedTopics,
                'today_topics' => $todayTopics,
                'week_topics' => $weekTopics,
                'month_topics' => $monthTopics,
                'hot_topics' => $hotTopics,
                'active_topics_by_posts' => $activeTopicsByPosts
            ]);
        } catch (\Exception $e) {
            return $this->fail('获取统计信息失败：' . $e->getMessage());
        }
    }
}